//
//  FRHttpNetworking.m
//  Health
//
//  Created by mykoma on 14-9-3.
//  Copyright (c) 2014年 scu.edu. All rights reserved.
//

#import "FRHttpNetworking.h"
#import <AFNetworking.h>
#import <SVProgressHUD/SVProgressHUD.h>

@interface FRHttpNetworking ()

@property (nonatomic, strong) AFHTTPRequestOperationManager * httpManager;

@end

@implementation FRHttpNetworking

MACRO_SHARED_INSTANCE_IMPLEMENTATION(FRHttpNetworking);

- (instancetype)init
{
    self = [super init];
    if (self) {
        _httpManager = [AFHTTPRequestOperationManager manager];
        _httpManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"text/plain", @"application/json", @"text/javascript", nil];
    }
    return self;
}

-(void)getFromServer:(NSString *)serverUrl
              action:(NSString *)action
          parameters:(NSArray *)parameters
             success:(void(^)(NSDictionary * responseObject))success
             failure:(void(^)(NSError *error))failure
{
    NSMutableString * serverUri = [[self formatAction:action serverUrl:serverUrl] mutableCopy];
    
    NSLog(@">>>>> Get request to (%@) with parameters: (%@)", serverUri, parameters);
    [parameters enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [serverUri appendFormat:@"/%@",obj];
    }];
    
    [self.httpManager GET:[self formatAction:action serverUrl:serverUrl]
               parameters:nil
                  success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSAssert([responseObject isKindOfClass:[NSDictionary class]], nil);
         NSLog(@"<<<<< Recived reponse (%@)", responseObject);
         success(responseObject);
     }
                  failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"<<<<< Recived error (%@)", error);
         failure(error);
     }];
}

-(void)postToServer:(NSString *)serverUrl
             action:(NSString *)action
         parameters:(id)parameters
            success:(void(^)(id responseObject))success
            failure:(void(^)(NSError *error))failure
{
    NSString * serverUri = [self formatAction:action serverUrl:serverUrl];
    NSLog(@">>>>> Post request to (%@) with parameters: (%@)", serverUri, parameters);
    
    [SVProgressHUD setBackgroundColor:[UIColor colorWithWhite:0.2 alpha:0.8]];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    if (![SVProgressHUD isVisible]) {
        [SVProgressHUD showWithStatus:@"数据加载中"];
    }
    
    [self.httpManager POST:serverUri
                parameters:parameters
                   success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSAssert([responseObject isKindOfClass:[NSDictionary class]] || [responseObject isKindOfClass:[NSArray class]], nil);
         NSLog(@"<<<<< Recived reponse (%@)\n for [%@]", responseObject, serverUri);
         [SVProgressHUD dismiss];
         success(responseObject);
     }
                   failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"<<<<< Recived error (%@)\n for [%@]", error, serverUri);
         [SVProgressHUD showErrorWithStatus:@"数据加载失败" maskType:SVProgressHUDMaskTypeNone];
         failure(error);
     }];
}

- (void)postToServer:(NSString *)serverUrl
              action:(NSString *)action
          parameters:(id)parameters
                data:(NSData *)data
                name:(NSString *)name
            mimeType:(NSString *)mimeType
            fileName:(NSString *)fileName
             success:(void (^)(NSDictionary *))success
             failure:(void (^)(NSError *))failure
{
    NSString * serverUri = [self formatAction:action serverUrl:serverUrl];
    NSLog(@">>>>> Post request to (%@", serverUri);
    [self.httpManager POST:serverUri
                parameters:parameters
 constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         [formData appendPartWithFileData:data name:name fileName:fileName mimeType:mimeType];
     }
                   success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSAssert([responseObject isKindOfClass:[NSDictionary class]], nil);
         NSLog(@"<<<<< Recived reponse (%@)", responseObject);
         success(responseObject);
     }
                   failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"<<<<< Recived error (%@)", error);
         failure(error);
     }];
}

#pragma mark - Private

-(NSString *)formatAction:(NSString *)action serverUrl:(NSString *)serverUrl
{
    NSString * formattedUrl = serverUrl;
    if (action.length > 0)
    {
        formattedUrl = [NSString stringWithFormat:@"%@/%@", serverUrl, action];
    }
    return formattedUrl;
}

@end
